import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Checkbox, Space, Table } from 'antd';
import { hasPermission } from 'libs';
import styles from './index.module.less';

function Footer(props) {
  const actions = props.actions || [];
  const length = props.selected.length;
  return length > 0 ? (
    <div className={styles.tableFooter}>
      <div className={styles.left}>{t('已选择')} <span>{length}</span> {t('项')}</div>
      <Space size="middle">
        {actions.map((item, index) => (
          <React.Fragment key={index}>{item}</React.Fragment>
        ))}
      </Space>
    </div>
  ) : null
}

function Header(props) {
  const columns = useMemo(() => props.columns || [], [props.columns]);
  const actions = props.actions || [];
  const onFieldsChange = props.onFieldsChange;


  useEffect(() => {
    const data = [];
    for (let [index, item] of columns.entries()) {
      if (!item.hide && (!item.auth || hasPermission(item.auth))) {
        data.push(index)
      }
    }
    onFieldsChange(data)
  }, [columns, onFieldsChange])

  return props.title || actions?.length ?
    <div className={[styles.toolbar, props.title ? '' : styles.noTitle].join(' ')}>
      <div className={styles.title}>{props.title}</div>
      <div className={styles.option}>
        <Space size={10}>
          {actions.map((item, index) => (
            <React.Fragment key={index}>{item}</React.Fragment>
          ))}
        </Space>
      </div>
    </div> : null
}

function TableCard({ columns = [], selected = [], batchActions = [], ...props }) {
  const rootRef = useRef();
  const [fields, setFields] = useState([]);

  return (
    <div ref={rootRef} className={[styles.tableCard, 'tableCard'].join(' ')} style={props.style || {}}>
      <Header
        title={props.title}
        columns={columns}
        actions={props.actions}
        rootRef={rootRef}
        onFieldsChange={setFields}
        onReload={props.onReload} />
      <div className={!props.outline && props.bordered ? '' : styles.outline}>
        <Table
          tableLayout={props.tableLayout || ''}
          rowKey={props.rowKey || 'id'}
          rowClassName={props.rowClassName || ''}
          loading={props.loading}
          sticky={props.sticky}
          scroll={props.scroll || false}
          size={props.size || false}
          onChange={props.onChange || null}
          onRow={props.onRow || null}
          bordered={props.bordered || false}
          columns={columns.filter((_, index) => fields.includes(index))}
          dataSource={props.dataSource}
          rowSelection={props.rowSelection}
          expandable={props.expandable}
          components={props.components}
          pagination={props.pagination} />
      </div>
      {selected.length ? <Footer selected={selected} actions={batchActions} /> : null}
    </div>
  )
}

TableCard.Header = Header;
TableCard.Footer = Footer;

export default TableCard